package com.joysuch.wwyt.api.mh.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.joysuch.wwyt.api.mh.entity.MonitorPointAPIData;
import com.joysuch.wwyt.api.mh.service.MonitorPointDataAPIService;
import com.joysuch.wwyt.bp.repository.BpEnterpriseInfoDao;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.storage.dto.GasData;
import com.joysuch.wwyt.mh.storage.dto.GasResultDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;

/**
 * 接入美卓的移动气体数据定时任务
 * @author zero
 * @since 2021/12/20 17:34
 */
@Slf4j
@Component
public class MonitorPointMeiZhuoTask {

    @Resource
    private BaseConfigService baseConfigService;
    

    private RestTemplate restTemplate;

    @Autowired
    private MonitorPointDataAPIService monitorPointDataAPIService;
    
    public MonitorPointMeiZhuoTask() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(15000);// 设置超时
        requestFactory.setReadTimeout(30000);
        this.restTemplate = new RestTemplate(requestFactory);
        List<HttpMessageConverter<?>> converters = this.restTemplate.getMessageConverters();
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof MappingJackson2HttpMessageConverter) {
                List<MediaType> mediaTypeList = new ArrayList<>(converter.getSupportedMediaTypes());
                mediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
                ((MappingJackson2HttpMessageConverter) converter).setSupportedMediaTypes(mediaTypeList);
            }
        }
    }

    @Scheduled(initialDelay = 15000, fixedDelay = 10 * 1000)
    public void mobileGasAccess() {
        List<Map<String, Object>> tenentIdAndOrgCode = baseConfigService.selectTenentIdAndOrgCodes(BaseConfigCodes.monitor_api_meizhuo_url, BaseConfigCodes.monitor_api_meizhuo_token);
        tenentIdAndOrgCode.forEach(m -> {
                    Long tenantId = (Long) m.get("tenentId");
                    String orgCode = (String) m.get("orgCode");
            //第三方对接气体监测数据,url以及token待定
            BaseConfig url = baseConfigService.findConfig(tenantId,orgCode,BaseConfigCodes.monitor_api_meizhuo_url);
            BaseConfig token = baseConfigService.findConfig(tenantId,orgCode,BaseConfigCodes.monitor_api_meizhuo_token);
            if (null != url && null != token && StringUtils.isNotBlank(url.getValue()) && StringUtils.isNotBlank(token.getValue())){
                GasResultDto gasResultDto = restTemplate.getForObject(url.getValue() + token.getValue(), GasResultDto.class);
                if (null != gasResultDto && CollectionUtils.isNotEmpty(gasResultDto.getData())){
                    //处理为保存的数据
                    List<MonitorPointAPIData> dataList = convertApiData(gasResultDto.getData(),url.getTenentId(),url.getOrgCode());
                    //保存数据
                    monitorPointDataAPIService.pushMonitorPointData(dataList,url.getTenentId(),url.getOrgCode());
                }
            }
        });
    }
    /**
     *   将获取的气体数据转为数据库需要的格式
     * @param gasDataList
     * @param tenantId
     * @param orgcode
     * @return
     */
    private List<MonitorPointAPIData> convertApiData(List<GasData> gasDataList, Long tenantId, String orgcode){
        List<MonitorPointAPIData> monitorPointAPIDataList = new ArrayList<>();
        for (GasData gasData : gasDataList) {
            MonitorPointAPIData apiData = new MonitorPointAPIData();
            apiData.setStationId(gasData.getId().toString());
            apiData.setTagName(gasData.getName());
            apiData.setTagValue(gasData.getValue());
            apiData.setTagTime(gasData.getTime());
            apiData.setPointUnit(gasData.getUnit());
            apiData.setPointType(gasData.getGas());
            apiData.setTenentId(tenantId.toString());
            apiData.setOrgCode(orgcode);
            apiData.setRemark(gasData.getStatus());
            monitorPointAPIDataList.add(apiData);
        }
        return monitorPointAPIDataList;
    }

    /**
     *  将获取的气体数据转为需要处理的格式数据
     * @param gasDataList
     * @param tenantId
     * @param orgcode
     * @return
     */
    private List<Map<String,Object>> convertData(List<GasData> gasDataList, Long tenantId, String orgcode){
        List<Map<String, Object>> data = new ArrayList<>();
        for (GasData gasData : gasDataList) {

            Map<String, Object> map = new HashMap<>();
            map.put("tag", gasData.getName());
            List<LinkedHashMap<String, Object>> values = new ArrayList<>();
            LinkedHashMap<String, Object> valOne = new LinkedHashMap<>();
            valOne.put("time", gasData.getTime().getTime());
            valOne.put("value",gasData.getValue());
            valOne.put("orgCode", orgcode);
            valOne.put("tenentId", tenantId);
            values.add(valOne);
            map.put("values", values);
            data.add(map);
        }
        return data;
    }
}
